﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Text;
using System.Web.Script.Services;
using HotelApp;
using System.IO;
using System.Globalization;
using System.Collections;
using System.Drawing.Imaging;
using System.Drawing;

namespace HotelWeb
{
    /// <summary>
    /// Summary description for NewsWebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class NewsWebService : System.Web.Services.WebService
    {
        #region NewsCategory

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string CreateNewsCategory()
        {
            NewsCategory obj = GetNewsCategoryFormUI();
            try
            {
                HotelAppOM.CreateNewsCategory(obj, Context.User.Identity.Name);
                return JsonResult(true, "success");
            }
            catch (Exception ex)
            {
                return JsonResult(false, ex.Message);
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string UpdateNewsCategory()
        {
            NewsCategory obj = GetNewsCategoryFormUI();
            try
            {
                HotelAppOM.UpdateNewsCategory(obj, Context.User.Identity.Name);
                return JsonResult(true, "success");
            }
            catch (Exception ex)
            {
                return JsonResult(false, ex.Message);
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string DeleteNewsCategory(string categoryCode)
        {
            try
            {
                int total = 0;
                NewsInfoDAO.ListNewsInfos(categoryCode, 0, 1, ref total);
                if (total > 0)
                    return JsonResult(false, "请先删除该类别下所有数据!");
                HotelAppOM.DeleteNewsCategory(categoryCode, Context.User.Identity.Name);
                return JsonResult(true, "success");
            }
            catch (Exception ex)
            {
                return JsonResult(false, ex.Message);
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public List<NewsCategory> ListNewsCategory()
        {
            return NewsCategoryDAO.ListCategories().ToList();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public NewsCategory GetCategory(string categoryCode)
        {
            return NewsCategoryDAO.GetCategory(categoryCode);
        }

        #endregion

        #region NewsInfo

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string CreateNewsInfo()
        {
            NewsInfo obj = GetNewsInfoFormUI();
            try
            {
                HotelAppOM.CreateNewsInfo(obj, "lxb");
                return JsonResult(true, "success");
            }
            catch (Exception ex)
            {
                return JsonResult(false, ex.Message);
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string UpdateNewsInfo()
        {
            NewsInfo obj = GetNewsInfoFormUI();
            try
            {
                NewsInfo info = NewsInfoDAO.GetNewsInfo(obj.NewsCode);
                if (info != null)
                {
                    info.NewsContent = obj.NewsContent;
                    info.NewsDesc = obj.NewsDesc;
                    info.NewsName = obj.NewsName;
                    HotelAppOM.UpdateNewsInfo(info, "lxb");
                    return JsonResult(true, "success");
                }

                return JsonResult(false, "failed");
            }
            catch (Exception ex)
            {
                return JsonResult(false, ex.Message);
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string DeleteNewsInfo(string newsCode)
        {
            try
            {
                HotelAppOM.DeleteNewsInfo(newsCode, "lxb");
                return JsonResult(true, "success");
            }
            catch (Exception ex)
            {
                return JsonResult(false, ex.Message);
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public NewsInfo GetNewsInfo(string newsCode)
        {
            return NewsInfoDAO.GetNewsInfo(newsCode);
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string ListNewsInfo(string categoryCode, int startIndex, int limit)
        {
            int totalCount = 0;
            List<NewsInfo> lst = NewsInfoDAO.ListNewsInfos(categoryCode, startIndex, limit, ref totalCount).ToList();
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            Context.Response.ContentType = "application/json";
            string strJson = jsSerializer.Serialize(lst);
            return "{total:" + totalCount + ",data:" + strJson + "}";
        }

        #endregion

        #region ImageCategory

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string CreateImageCategory()
        {
            ImageCategory obj = GetImageCategoryFormUI();
            try
            {
                HotelAppOM.CreateImageCategory(obj, Context.User.Identity.Name);
                return JsonResult(true, "success");
            }
            catch (Exception ex)
            {
                return JsonResult(false, ex.Message);
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string UpdateImageCategory()
        {
            ImageCategory obj = GetImageCategoryFormUI();
            try
            {
                HotelAppOM.UpdateImageCategory(obj, Context.User.Identity.Name);
                return JsonResult(true, "success");
            }
            catch (Exception ex)
            {
                return JsonResult(false, ex.Message);
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string DeleteImageCategory(string categoryCode)
        {
            try
            {
                int total = 0;
                ImageInfoDAO.ListImageInfos(categoryCode, 0, 1, ref total);
                if (total > 0)
                    return JsonResult(false, "请先删除该类别下所有数据!");

                HotelAppOM.DeleteImageCategory(categoryCode, Context.User.Identity.Name);
                return JsonResult(true, "success");
            }
            catch (Exception ex)
            {
                return JsonResult(false, ex.Message);
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public List<ImageCategory> ListImageCategory()
        {
            return ImageCategoryDAO.ListCategories().ToList();
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public ImageCategory GetImageCategory(string categoryCode)
        {
            return ImageCategoryDAO.GetCategory(categoryCode);
        }

        #endregion

        #region ImageInfo

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public JsonResult CreateImageInfo()
        {
            ImageInfo obj = GetImageInfoFormUI();
            try
            {
                string message = string.Empty;
                if (!UploadImage(obj, ref message))
                    //return JsonResult(false, message);
                    return new JsonResult(false, JsonResult(true, message), message);
                HotelAppOM.CreateImageInfo(obj, Context.User.Identity.Name);
                //return JsonResult(true, "success");
                return new JsonResult(true, "success", "success");
            }
            catch (Exception ex)
            {
                //return JsonResult(false, ex.Message);
                return new JsonResult(false, "success", ex.Message);
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string UpdateImageInfo()
        {
            ImageInfo obj = GetImageInfoFormUI();
            try
            {
                ImageInfo info = ImageInfoDAO.GetImageInfo(obj.ImageCode);
                if (info != null)
                {
                    info.ImageName = obj.ImageName;
                    info.ImageDesc = obj.ImageDesc;
                    HotelAppOM.UpdateImageInfo(info, Context.User.Identity.Name);
                    return JsonResult(true, "success");
                }

                return JsonResult(false, "failed");
            }
            catch (Exception ex)
            {
                return JsonResult(false, ex.Message);
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string DeleteImageInfo(string imageCode)
        {
            try
            {
                HotelAppOM.DeleteImageInfo(imageCode, Context.User.Identity.Name);
                return JsonResult(true, "success");
            }
            catch (Exception ex)
            {
                return JsonResult(false, ex.Message);
            }
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public ImageInfo GetImageInfo(string imageCode)
        {
            return ImageInfoDAO.GetImageInfo(imageCode);
        }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string ListImageInfo(string categoryCode, int startIndex, int limit)
        {
            int totalCount = 0;
            List<ImageInfo> lst = ImageInfoDAO.ListImageInfos(categoryCode, startIndex, limit, ref totalCount).ToList();
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            Context.Response.ContentType = "application/json";
            string strJson = jsSerializer.Serialize(lst);
            return "{total:" + totalCount + ",data:" + strJson + "}";
        }

        #endregion

        #region private methods

        private void ResponseWrite<T>(List<T> lst)
        {
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
            //jsSerializer.RegisterConverters(new List<JavaScriptConverter>(new JavaScriptConverter[] { new SqlDateTimeConverter() }));
            Context.Response.ContentType = "application/json";
            Context.Response.Write(jsSerializer.Serialize(lst));
        }

        private void ResponseWrite(string strJson)
        {
            Context.Response.ContentType = "application/json";
            Context.Response.Write(strJson);
        }

        private string JsonResult(bool isSuccess, string message)
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("{");
            if (isSuccess)
            {
                stringBuilder.AppendFormat("success:true,");
            }
            else
            {
                stringBuilder.AppendFormat("success:false,");
            }
            stringBuilder.Append("errors:{");
            stringBuilder.AppendFormat("clientCode:'{0}'", message);
            stringBuilder.Append("}}");
            return stringBuilder.ToString();
        }

        private void ExecuteResult(bool isSuccess, string message)
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("{");
            if (isSuccess)
            {
                stringBuilder.AppendFormat("success:true,");
            }
            else
            {
                stringBuilder.AppendFormat("success:false,");
            }
            stringBuilder.Append("errors:{");
            stringBuilder.AppendFormat("clientCode:'{0}'", message);
            stringBuilder.Append("}}");
            this.Context.Response.Write(stringBuilder.ToString());
        }

        private NewsCategory GetNewsCategoryFormUI()
        {
            NewsCategory obj = new NewsCategory();
            obj.CategoryCode = this.Context.Request.Form.Get("CategoryCode");
            obj.CategoryName = this.Context.Request.Form.Get("CategoryName");
            obj.CategoryDesc = this.Context.Request.Form.Get("CategoryDesc");

            return obj;
        }

        private NewsInfo GetNewsInfoFormUI()
        {
            NewsInfo obj = new NewsInfo();
            obj.NewsCode = this.Context.Request.Form.Get("NewsCode");
            obj.CategoryCode = this.Context.Request.Form.Get("CategoryCode");
            obj.NewsName = this.Context.Request.Form.Get("NewsName");
            obj.NewsDesc = this.Context.Request.Form.Get("NewsDesc");
            obj.NewsContent = this.Context.Request.Form.Get("NewsContent");
            obj.Creator = Context.User.Identity.Name;

            return obj;
        }

        private ImageCategory GetImageCategoryFormUI()
        {
            ImageCategory obj = new ImageCategory();
            obj.CategoryCode = this.Context.Request.Form.Get("CategoryCode");
            obj.CategoryName = this.Context.Request.Form.Get("CategoryName");
            obj.CategoryDesc = this.Context.Request.Form.Get("CategoryDesc");

            return obj;
        }

        private ImageInfo GetImageInfoFormUI()
        {
            ImageInfo obj = new ImageInfo();
            obj.ImageName = this.Context.Request.Form.Get("ImageName");
            obj.CategoryCode = this.Context.Request.Form.Get("CategoryCode");
            obj.ImageDesc = this.Context.Request.Form.Get("ImageDesc");
            obj.Creator = Context.User.Identity.Name;

            return obj;
        }

        private bool UploadImage(ImageInfo obj, ref string message)
        {
            String aspxUrl = Context.Request.Path.Substring(0, Context.Request.Path.LastIndexOf("/") + 1);

            //文件保存目录路径
            String savePath = "upload/";

            //文件保存目录URL
            String saveUrl = aspxUrl + "upload/";

            //定义允许上传的文件扩展名
            Hashtable extTable = new Hashtable();
            extTable.Add("image", "gif,jpg,jpeg,png,bmp");

            //最大文件大小
            int maxSize = 1000000;

            HttpPostedFile imgFile = Context.Request.Files["file"];
            if (imgFile == null)
            {
                message = "请选择文件";
                return false;
            }

            String dirPath = Context.Server.MapPath(savePath);
            if (!Directory.Exists(dirPath))
            {
                message = "上传目录不存在";
                return false;
            }

            String fileName = imgFile.FileName;
            String fileExt = Path.GetExtension(fileName).ToLower();

            if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize)
            {
                message = "上传文件大小超过限制";
                return false;
            }

            if (String.IsNullOrEmpty(fileExt))
            {
                message = "只能上传图片";
                return false;
            }

            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            String newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            String filePath = dirPath + newFileName;
            string thumbName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + "_thumbnail" + fileExt;

            imgFile.SaveAs(filePath);

            if (!ToThumbnailImages(filePath, dirPath + thumbName, 270, ref message))
                return false;

            obj.FileName = fileName.Substring(fileName.LastIndexOf("\\") + 2);
            obj.ImageType = fileExt.Substring(1);
            obj.FileNewName = newFileName;
            obj.FilePath = savePath + newFileName;
            obj.ThumbnailPath = savePath + thumbName;

            return true;
        }

        #region 生成略缩图

        static Hashtable htmimes = new Hashtable();
        internal readonly string AllowExt = ".jpe|.jpeg|.jpg|.png|.tif|.tiff|.bmp";

        /// <summary>
        /// 获取图像编码解码器的所有相关信息
        /// </summary>
        /// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
        /// <returns>返回图像编码解码器的所有相关信息</returns>
        static ImageCodecInfo GetCodecInfo(string mimeType)
        {
            ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo ici in CodecInfo)
            {
                if (ici.MimeType == mimeType) return ici;
            }
            return null;
        }

        /// <summary>
        /// 检测扩展名的有效性
        /// </summary>
        /// <param name="sExt">文件名扩展名</param>
        /// <returns>如果扩展名有效,返回true,否则返回false.</returns>
        bool CheckValidExt(string sExt)
        {
            bool flag = false;
            string[] aExt = AllowExt.Split('|');
            foreach (string filetype in aExt)
            {
                if (filetype.ToLower() == sExt)
                {
                    flag = true;
                    break;
                }
            }
            return flag;
        }

        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="image">Image 对象</param>
        /// <param name="savePath">保存路径</param>
        /// <param name="ici">指定格式的编解码参数</param>
        void SaveImage(System.Drawing.Image image, string savePath, ImageCodecInfo ici)
        {
            //设置 原图片 对象的 EncoderParameters 对象
            EncoderParameters parameters = new EncoderParameters(1);
            parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ((long)90));
            image.Save(savePath, ici, parameters);
            parameters.Dispose();
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="sourceImagePath">原图片路径(相对路径)</param>
        /// <param name="thumbnailImagePath">生成的缩略图路径,如果为空则保存为原图片路径(相对路径)</param>
        /// <param name="thumbnailImageWidth">缩略图的宽度（高度与按源图片比例自动生成）</param>
        public bool ToThumbnailImages(string sourceImagePath, string thumbnailImagePath, int thumbnailImageWidth, ref string message)
        {
            string SourceImagePath = sourceImagePath;
            string ThumbnailImagePath = thumbnailImagePath;
            int ThumbnailImageWidth = thumbnailImageWidth;
            string sExt = SourceImagePath.Substring(SourceImagePath.LastIndexOf(".")).ToLower();
            if (SourceImagePath.ToString() == System.String.Empty)
            {
                message = "原图片为空!";
                return false;
            } 
            if (!CheckValidExt(sExt))
            {
                message = "原图片文件格式不正确,支持的格式有[ " + AllowExt + " ]";
                return false;
            }
            //从 原图片 创建 Image 对象
            System.Drawing.Image image = System.Drawing.Image.FromFile(SourceImagePath);
            int num = ((ThumbnailImageWidth / 4) * 3);
            int width = image.Width;
            int height = image.Height;
            //计算图片的比例
            if ((((double)width) / ((double)height)) >= 1.3333333333333333f)
            {
                num = ((height * ThumbnailImageWidth) / width);
            }
            else
            {
                ThumbnailImageWidth = ((width * num) / height);
            }
            if ((ThumbnailImageWidth < 1) || (num < 1))
            {
                message = "请上传长度大于300，高度大于150的图片!";
                return false;
            }
            //用指定的大小和格式初始化 Bitmap 类的新实例
            Bitmap bitmap = new Bitmap(ThumbnailImageWidth, num, PixelFormat.Format32bppArgb);
            //从指定的 Image 对象创建新 Graphics 对象
            Graphics graphics = Graphics.FromImage(bitmap);
            //清除整个绘图面并以透明背景色填充
            graphics.Clear(Color.Transparent);
            //在指定位置并且按指定大小绘制 原图片 对象
            graphics.DrawImage(image, new Rectangle(0, 0, ThumbnailImageWidth, num));
            image.Dispose();
            try
            {
                //将此 原图片 以指定格式并用指定的编解码参数保存到指定文件 
                string savepath = (ThumbnailImagePath == null ? SourceImagePath : ThumbnailImagePath);
                htmimes[".jpe"] = "image/jpeg";
                htmimes[".jpeg"] = "image/jpeg";
                htmimes[".jpg"] = "image/jpeg";
                htmimes[".png"] = "image/png";
                htmimes[".tif"] = "image/tiff";
                htmimes[".tiff"] = "image/tiff";
                htmimes[".bmp"] = "image/bmp";
                SaveImage(bitmap, savepath, GetCodecInfo((string)htmimes[sExt]));
            }
            catch (System.Exception e)
            {
                message = e.Message;
                return false;
            }
            finally
            {
                bitmap.Dispose();
                graphics.Dispose();
            }

            return true;
        }

        #endregion

        #endregion
    }

    public class JsonResult
    {
        public bool IsSuccess { get; set; }
        public string ResponseContent { get; set; }
        public string Message { get; set; }

        public JsonResult(bool isSuccess, string content, string message)
        {
            this.IsSuccess = isSuccess;
            this.ResponseContent = content;
            this.Message = message;
        }

        public JsonResult()
        { 
            
        }
    }
}
